﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace EzDesk.Utility.Log
{
    public class LogEx
    {
        // Fields
        private const string LOG_TAG_FILLTER = null;
        private static string _allLogFilePath;
        private static bool _logEnable = true;

        public static string CurrentLogFilePath
        {
            get { return _allLogFilePath; }
        }

        // Methods
        static LogEx()
        {
            _allLogFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "ALL_TRACE_" + DateTime.Now.ToString("yyyyMMdd") + ".LOG";
            _logEnable = true;
        }

        // Methods
        public static void EnableWritingFile(bool isenable)
        {
            _logEnable = isenable;
        }

        public static void ERROR(string component, string msg, Exception ex)
        {
            string errorString = ex == null ? "" : ex.ToString();
            msg = msg + Environment.NewLine + " [Exception: ]" + errorString;
            WriteConsole("ERROR :", component, msg);
        }

        public static void EXCEPT(string component, string msg, Exception ex)
        {
            string errorString = ex == null ? "" : ex.ToString();
            msg = msg + Environment.NewLine + " [Exception: ]" + errorString;
            WriteConsole("EXCEPT:", component, msg);
        }

        public static void EXCEPT(string component, string msg)
        {
            var exception = new ApplicationException(msg);
            EXCEPT(component, msg, exception);
        }

        public static void TRACE(string component, string msg)
        {
            WriteConsole("TRACE :", component, msg);
        }

        public static void WARN(string component, string msg)
        {
            WriteConsole("WARN  :", component, msg);
        }

        private static void WriteConsole(string level, string component, string msg)
        {
            if (_logEnable)
            {
                WriteFile(_allLogFilePath, level, component, msg);

                Debug.WriteLine(DateTime.Now.ToString("[HH:mm:ss:fff]") + level + component + msg);
            }
        }



        private static void WriteFile(string filepath, string level, string component, string msg)
        {
            try
            {
                lock (filepath)
                {
                    StreamWriter writer = File.AppendText(filepath);
                    string str = msg;
                    string str3 = DateTime.Now.ToString("[HH:mm:ss:fff]") + level + component + str;
                    writer.WriteLine(str3);
                    writer.Close();
                }
            }
            catch (Exception)
            {
            }
        }


    }


}
